import time
import random

class PIDController:
    def __init__(self, kp, ki, kd, setpoint):
        self.kp = kp
        self.ki = ki
        self.kd = kd
        self.setpoint = setpoint
        self.integral = 0
        self.last_error = 0
        self.last_time = time.time()

    def update(self, measurement):
        # time.sleep(random.randint(1,3))
        current_time = time.time()
        dt = current_time - self.last_time
        error = self.setpoint - measurement
        self.integral += error * dt
        derivative = (error - self.last_error) / dt

        output = self.kp * error + self.ki * self.integral + self.kd * derivative

        self.last_error = error
        self.last_time = current_time

        return output

# 初始化PID控制器
pid = PIDController(kp=1, ki=0.1, kd=0.01, setpoint=50)

# 模拟温度控制
current_temp = 0
# while True:
while abs(current_temp - pid.setpoint) > 0.01 :
    time.sleep(1)
    control_output = pid.update(current_temp)
    print(f"当前温度：{current_temp}°C, 控制输出：{control_output:.2f}")
    current_temp += control_output
    time.sleep(1)